<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择类型状态" clearable style="width: 180px">
          <el-option label="正常" value="0"/>
          <el-option label="停用" value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:type:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-card class="message-card" shadow="hover">
      <el-collapse accordion
                   @change="handleCollapseChange">
        <el-collapse-item
            v-for="type in typeList"
            :key="type.typeId"
            :name="type.typeId"
            :disabled="type.status === '1'"
        >
          <template #title>
            <el-text size="large"> {{ type.typeName }}</el-text>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <el-switch
                v-model="type.status"
                active-value="0"
                inactive-value="1"
                v-hasPermi="['system:type:edit']"
                size="small"
                @change="handleStatusChange(type)"
            ></el-switch>
            <el-row :gutter="20">
              <el-col :span="1.5">
              </el-col>
              <el-col :span="1.5">
                <el-button
                    type="text"
                    plain
                    icon="Delete"
                    @click="handleDelete(type)"
                    v-hasPermi="['system:type:remove']"
                >
                </el-button>
              </el-col>
            </el-row>
          </template>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                  type="primary"
                  plain
                  icon="Plus"
                  @click="handlePresetAdd(type.typeId)"
              >新增
              </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
          <el-table v-loading="loading" :data="presetList" @selection-change="handleSelectionChange" border>
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="序号" align="center" type="index" width="55px"/>
            <el-table-column label="预设问题标题" align="center" prop="preTitle" width="200px"/>
            <el-table-column label="创建人" align="center" prop="createBy"/>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180px"/>
            <el-table-column label="更新人" align="center" prop="updateBy"/>
            <el-table-column label="更新时间" align="center" prop="updateTime" width="180px"/>
            <el-table-column label="状态" align="center" prop="status">
              <template #default="scope" >
                <el-switch
                    v-model="scope.row.status"
                    active-value="0"
                    inactive-value="1"
                    v-show="showButtonOrNot(scope.row)"
                    @change="handlePresetStatusChange(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180"
                             fixed="right">
              <template #default="scope">
                <el-button link type="primary" icon="Edit" v-if="showButtonOrNot(scope.row)" @click="handlePresetUpdate(scope.row)">修改</el-button>
                <el-button link type="primary" icon="Delete" v-if="showButtonOrNot(scope.row)" @click="handlePresetDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </el-card>

    <!-- 添加或修改问题类型对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="typeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="问题类型" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入问题类型名称"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改预设问题对话框 -->
    <el-dialog :title="title" v-model="openPreset" width="500px" append-to-body>
      <el-form ref="presetRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="预设问题" prop="preTitle">
          <el-input v-model="form.preTitle" placeholder="请输入预设问题标题"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPresetForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Type">
import {listType, getType, delType, addType, updateType, changeTypeStatus} from "@/api/system/type";
import {addPreset, delPreset, getPreset, listPreset, updatePreset} from "@/api/system/preset.js";
import {getInfo} from "@/api/login.js";
import {changePresetStatus} from "@/api/system/preset.js";

const {proxy} = getCurrentInstance();

const typeList = ref([]);
const presetList = ref([]);
const open = ref(false);
const openPreset = ref(false);
const loading = ref(true);
const refreshTable = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const showButton = ref(true);
const total = ref(0);
const title = ref("");
const userSchoolId = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    typeName: null,
    status: null,
  },
  PresetQueryParams: {
    pageNum: 1,
    pageSize: 10,
    preTitle: null,
    status: null,
    typeId: null,
    schoolId: null
  },
  rules: {
    typeName: [
      {required: true, message: "问题类型不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules,PresetQueryParams} = toRefs(data);

/** 查询问题类型列表 */
function getList() {
  loading.value = true;
  listType(queryParams.value).then(response => {
    typeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询预设问题列表 */
function getPresetList(typeId) {
  loading.value = true;
  PresetQueryParams.value.typeId = typeId;
  PresetQueryParams.value.schoolId = userSchoolId.value;
  listPreset(PresetQueryParams.value).then(response => {
    presetList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  openPreset.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    typeId: null,
    typeName: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  };
  proxy.resetForm("typeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.status = null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.typeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加问题类型";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _typeId = row.typeId || ids.value
  getType(_typeId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改问题类型";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["typeRef"].validate(valid => {
    if (valid) {
      if (form.value.typeId != null) {
        updateType(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addType(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _typeIds = row.typeId || ids.value;
  proxy.$modal.confirm('是否确认删除问题类型编号为"' + _typeIds + '"的数据项？').then(function () {
    return delType(_typeIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/type/export', {
    ...queryParams.value
  }, `type_${new Date().getTime()}.xlsx`)
}

/** 状态修改  */
function handleStatusChange(type) {
  let text = type.status === "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + type.typeName + '"类型吗?').then(function () {
    return changeTypeStatus(type.typeId, type.status);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    type.status = type.status === "0" ? "1" : "0";
  });
};

/** 状态修改  */
function handlePresetStatusChange(row) {
  refreshTable.value = false;
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '"吗?').then(function () {
    return changePresetStatus(row.preId, row.status);
  }).then(() => {
    refreshTable.value = true;
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0";
  });
};

function handleCollapseChange(type) {
  getPresetList(type)
};

function handlePresetUpdate(row){
  reset();
  console.log(row.schoolId)
  const _preId = row.preId || ids.value
  getPreset(_preId).then(response => {
    form.value = response.data;
    openPreset.value = true;
    title.value = "修改预设问题";
  });
}

/** 提交按钮 */
function submitPresetForm() {
  proxy.$refs["presetRef"].validate(valid => {
    if (valid) {
      if (form.value.preId != null) {
        updatePreset(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openPreset.value = false;
          // 新增下面这行代码
          getPresetList(form.value.typeId); // 刷新当前类型的预设问题列表
        });
      } else {
        addPreset(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openPreset.value = false;
          // 新增下面这行代码
          getPresetList(form.value.typeId); // 刷新当前类型的预设问题列表
        });
      }
    }
  });
}

function handlePresetDelete(row) {
  proxy.$modal.confirm('确认要删除"' + row.preTitle + '"吗?').then(function () {
    return delPreset(row.preId);
  }).then(() => {
    getPresetList(row.typeId); // 新增这行刷新当前类型
    proxy.$modal.msgSuccess("删除成功");
  }).catch(function () {
  });
}

function getUserInfo(){
  getInfo().then(res => {
    userSchoolId.value = res.user.schoolId;
  });
}

function showButtonOrNot(row){
  if (userSchoolId.value === null|| userSchoolId.value === ''|| userSchoolId.value === '0'){
    return true;
  }else if (userSchoolId.value === row.schoolId){
    return true;
  }else {
    return false;
  }
}

/** 新增按钮操作 */
function handlePresetAdd(typeId) {
  reset();
  openPreset.value = true;
  title.value = "添加预设问题";
  form.value.typeId = typeId;
}
getList();
getUserInfo();
</script>
